﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;

namespace ScrumFactory.Windows.Helpers {

    

    public class LocalizedEnum : TypeConverter {
        
        public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) {
            return (sourceType.Equals(typeof(Enum)));
        }

        public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType) {
            return (destinationType.Equals(typeof(String)));
        }

        public override object ConvertFrom(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value) {
            return base.ConvertFrom(context, culture, value);
        }

        public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType) {
            if (!destinationType.Equals(typeof(String))) {
                throw new ArgumentException("Can only convert to string.", "destinationType");
            }

            if (!value.GetType().BaseType.Equals(typeof(Enum))) {
                throw new ArgumentException("Can only convert an instance of enum.", "value");
            }



            System.Reflection.Assembly assembly = System.Reflection.Assembly.GetAssembly(value.GetType());             
            System.Resources.ResourceManager r = new System.Resources.ResourceManager(assembly.GetName().Name + ".Properties.Resources", assembly);
            
            string name = value.ToString();

            if(r==null)
                return name;

            string localizedName = r.GetString(name);
            return (localizedName==null) ? name: localizedName;
            
        }
    } 

}
